/** @format */
import { getToday } from '../getToday'
import { TASK_RATE_TYPE } from '../../../constants'
import { getUserOrderlist } from '../getUserOrderlist'
import { OEDER_DB_NAME } from '../../../db'
import { resultsModel } from '../../../sdk'
import { BaseDao } from '../../../sdk'
import { CODE_TYPES } from '../../../errorCode'
import { formatDate } from '../date'

export default async function updateGrowOrderGoods(
  context: IContext<IParams>,
  { userInfo, activityInfo }: IControllerInfos
): Promise<IPreUpdateQuery> {
  const taskType = 'order'
  const { reward, itemIds, rateType, times } = activityInfo?.tasks?.[taskType] || {}
  let orderdao: IBaseDao = new BaseDao(context, OEDER_DB_NAME)
  const orderList =
  rateType === TASK_RATE_TYPE.EVERYDAY
      ? await orderdao.find({
          openId: userInfo.openId,
          activityId: userInfo.activityId,
          createDay: getToday()
        })
      : await orderdao.find({
          openId: userInfo.openId,
          activityId: userInfo.activityId
        })

  const completeTimes = orderList?.length || 0

  if (!activityInfo?.tasks?.[taskType]) return {}
  // 每日任务或者是永久任务的任务且已完成
  if (rateType !== TASK_RATE_TYPE.NOLIMIT && completeTimes >= times) {
    return {}
  }

  const today = getToday()
  //设置查询淘宝订单时间
  let startTime = Date.now()
  if (rateType === TASK_RATE_TYPE.EVERYDAY) {
    let TodayTime = formatDate(today).getTimestamp()
    startTime = TodayTime > userInfo.createTime ? TodayTime : userInfo.createTime
  } else {
    startTime = userInfo.createTime || activityInfo?.startTime || Date.now()
  }
  const orderResult = await getUserOrderlist(
    context,
    //@ts-ignore
    startTime,
    Date.now()
  )

  const itemIdsArr = itemIds.split(',').map(v => +v)

  let projection = {
    $inc: {
      [`remainTimes.${taskType}`]: 0
    },
    $set: {}
  }
  //筛选符合任务的订单并添加到下单表
  let targetOrders = []
  orderResult.forEach(v => {
    if (
      // 商品订单包含目标商品 且orderId为新订单
      itemIdsArr.includes(v.itemId) &&
      // @ts-ignore
      !orderList.some(order => order.orderId === v.orderId) &&
      !targetOrders.some(order => order.orderId === v.orderId)
    ) {
      if (targetOrders.length + completeTimes >= times && rateType !== TASK_RATE_TYPE.NOLIMIT) {
        return
      }
      targetOrders.push({
        openId: userInfo.openId,
        activityId: activityInfo._id,
        itemId: v.itemId,
        orderId: v.orderId,
        tId: v.tId,
        createTime: Date.now(),
        createDay: today
      })
    }
  })
  if (targetOrders?.length) {
    const result = await orderdao.insertMany(targetOrders)
    if (!result || result.length === 0) {
      // @ts-ignore
      return resultsModel.error(CODE_TYPES.SYSTEM_ERROR, '订单任务更新失败')
    }
    projection.$inc[`remainTimes.${taskType}`] = result.length * reward
  }

  return projection
}
